<template>
  <div class="app-container">
    <!-- 遮罩层 -->
    <transition name="fade">
      <div
        v-if="!isCollapse"
        class="sidebar-mask"
        @click="closeSidebar"
      />
    </transition>

    <!-- 侧边栏 -->
    <transition name="slide-left">
      <el-aside
        v-if="!isCollapse"
        :width="'220px'"
        :class="['sidebar-container', { 'is-collapse': isCollapse }]"
        @click.stop
      >
        <!-- Logo -->
        <div class="logo-container">
          <div class="logo">
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect width="32" height="32" rx="6" fill="#409EFF"/>
              <path d="M8 12h16v2H8v-2zm0 4h16v2H8v-2zm0 4h12v2H8v-2z" fill="white"/>
              <circle cx="6" cy="13" r="1" fill="white"/>
              <circle cx="6" cy="17" r="1" fill="white"/>
              <circle cx="6" cy="21" r="1" fill="white"/>
            </svg>
          </div>
          <h1 v-show="!isCollapse" class="title">项目管理系统</h1>
        </div>
        
        <div class="sidebar-content">
          <!-- 菜单 -->
          <el-scrollbar class="menu-scrollbar">
            <el-menu
              :default-active="activeMenu"
              :unique-opened="true"
              class="sidebar-menu"
              background-color="transparent"
              text-color="#bfcbd9"
              active-text-color="#409EFF"
            >
              <sidebar-item
                v-for="route in routes"
                :key="route.path"
                :item="route"
                :base-path="'/'"
                :is-collapse="isCollapse"
              />
            </el-menu>
          </el-scrollbar>
        </div>
      </el-aside>
    </transition>
    
    <!-- 主体区域 -->
    <el-container class="main-container">
      <!-- 头部 -->
      <el-header class="header">
        <div class="header-left">
          <div class="toggle-icon-wrapper" @click="toggleSidebar">
            <el-icon class="toggle-icon">
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </div>
          <breadcrumb />
        </div>
        <div class="header-right">
          <notification-dropdown />
          
          <el-tooltip content="全屏" placement="bottom">
            <el-icon class="header-icon" @click="toggleFullScreen">
              <FullScreen />
            </el-icon>
          </el-tooltip>
          
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="avatarUrl">
                {{ (userStore.userInfo?.name || userStore.userInfo?.username || '用户').charAt(0).toUpperCase() }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.name || userStore.userInfo?.email || '用户' }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item v-if="userStore.hasRole('admin')" command="settings">系统设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 内容区域 -->
      <el-main class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import SidebarItem from '@/components/SidebarItem.vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import NotificationDropdown from '@/components/notification/NotificationDropdown.vue'
import { getAvatarUrl as getAvatarUrlUtil } from '@/utils/avatar'

// 默认头像的SVG
const defaultAvatar = 'data:image/svg+xml;base64,' + btoa(`
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle cx="16" cy="16" r="16" fill="#409EFF"/>
  <circle cx="16" cy="12" r="4" fill="white"/>
  <path d="M8 24c0-4.4 3.6-8 8-8s8 3.6 8 8" fill="white"/>
</svg>
`)

// 获取路由信息
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 计算头像URL
const avatarUrl = computed(() => {
  const url = getAvatarUrlUtil(userStore.userInfo?.avatar)
  return url || defaultAvatar
})

// 侧边栏折叠状态（默认隐藏）
const isCollapse = ref(true)

// 关闭侧边栏
const closeSidebar = () => {
  isCollapse.value = true
  // 保存状态到本地存储
  localStorage.setItem('sidebarStatus', '1')
}

// 缓存的视图
const cachedViews = ref(['Dashboard'])

// 计算当前激活的菜单
const activeMenu = computed(() => {
  const { meta, path } = route
  if (meta?.activeMenu) {
    return meta.activeMenu as string
  }
  return path || ''
})

// 获取路由列表（过滤掉隐藏的路由）
const routes = computed(() => {
  const routes = router.options.routes.find(route => route.path === '/')
  if (routes && routes.children) {
    return routes.children.filter(route => !route.meta?.hideInMenu)
  }
  return []
})

// 切换侧边栏折叠状态
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
  // 保存状态到本地存储
  localStorage.setItem('sidebarStatus', isCollapse.value ? '1' : '0')
}

// 切换全屏
const toggleFullScreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    }
  }
}

// 处理下拉菜单命令
const handleCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      await userStore.logout()
      router.push('/login')
      break
  }
}

// 处理 ESC 键关闭侧边栏
const handleEscKey = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && !isCollapse.value) {
    closeSidebar()
  }
}

// 初始化
onMounted(() => {
  // 从本地存储中恢复侧边栏状态
  // 默认隐藏，如果用户之前打开过，则恢复打开状态
  const savedCollapse = localStorage.getItem('sidebarStatus')
  if (savedCollapse !== null) {
    isCollapse.value = savedCollapse === '1'
  } else {
    // 首次访问，默认隐藏
    isCollapse.value = true
  }
  
  // 监听 ESC 键
  document.addEventListener('keydown', handleEscKey)
})

// 清理
onUnmounted(() => {
  document.removeEventListener('keydown', handleEscKey)
})
</script>

<style scoped>
.app-container {
  height: 100%;
  display: flex;
}

.sidebar-container {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  height: 100vh;
  width: 260px;
  background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 4px 0 32px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.05);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-container {
  height: 72px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.15) 0%, rgba(64, 158, 255, 0.08) 100%);
  border-bottom: 1px solid rgba(255, 255, 255, 0.12);
  transition: all 0.3s ease;
  position: relative;
}

.logo-container::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, rgba(64, 158, 255, 0.3) 50%, transparent 100%);
}

.logo {
  width: 40px;
  height: 40px;
  margin-right: 14px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  flex-shrink: 0;
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.3));
}

.logo:hover {
  transform: scale(1.15) rotate(8deg);
  filter: drop-shadow(0 4px 8px rgba(64, 158, 255, 0.5));
}

.title {
  color: #fff;
  font-size: 19px;
  font-weight: 700;
  white-space: nowrap;
  overflow: hidden;
  letter-spacing: 0.8px;
  background: linear-gradient(135deg, #ffffff 0%, rgba(255, 255, 255, 0.85) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sidebar-menu {
  border-right: none;
  background: transparent;
  padding: 0;
}

.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 20px 16px;
}

.menu-scrollbar {
  flex: 1;
}

:deep(.menu-scrollbar .el-scrollbar__wrap) {
  overflow-x: hidden;
}

:deep(.menu-scrollbar .el-scrollbar__view) {
  padding: 0;
}

:deep(.sidebar-menu .el-menu-item),
:deep(.sidebar-menu .el-sub-menu__title) {
  height: 52px;
  line-height: 52px;
  margin-bottom: 6px;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 0 16px !important;
  color: rgba(255, 255, 255, 0.75);
  font-size: 14px;
  position: relative;
}

:deep(.sidebar-menu .el-menu-item::before),
:deep(.sidebar-menu .el-sub-menu__title::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%) scaleY(0);
  width: 3px;
  height: 0;
  background: linear-gradient(180deg, #409EFF 0%, #66b1ff 100%);
  border-radius: 0 2px 2px 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.sidebar-menu .el-menu-item:hover::before),
:deep(.sidebar-menu .el-sub-menu__title:hover::before) {
  transform: translateY(-50%) scaleY(1);
  height: 24px;
}

:deep(.sidebar-menu .el-menu-item:hover),
:deep(.sidebar-menu .el-sub-menu__title:hover) {
  background: rgba(255, 255, 255, 0.12) !important;
  color: rgba(255, 255, 255, 1) !important;
  transform: translateX(6px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(64, 158, 255, 0.1);
}

:deep(.sidebar-menu .el-menu-item.is-active) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%) !important;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.2);
  color: #ffffff !important;
  font-weight: 600;
  position: relative;
  transform: translateX(4px);
}

:deep(.sidebar-menu .el-menu-item.is-active::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 32px;
  background: #ffffff;
  border-radius: 0 3px 3px 0;
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.5);
}

:deep(.sidebar-menu .el-menu-item.is-active::after) {
  content: '';
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 6px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  box-shadow: 0 0 4px rgba(255, 255, 255, 0.6);
}

:deep(.sidebar-menu .el-menu-item.is-active .menu-item-text),
:deep(.sidebar-menu .el-menu-item.is-active .el-icon) {
  color: #ffffff !important;
}

:deep(.sidebar-menu .el-sub-menu.is-active > .el-sub-menu__title) {
  color: rgba(255, 255, 255, 1) !important;
  background: rgba(64, 158, 255, 0.2) !important;
  font-weight: 600;
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

:deep(.sidebar-menu .el-sub-menu.is-active > .el-sub-menu__title::before) {
  transform: translateY(-50%) scaleY(1);
  height: 28px;
}

:deep(.sidebar-menu .el-sub-menu.is-active > .el-sub-menu__title .menu-item-text),
:deep(.sidebar-menu .el-sub-menu.is-active > .el-sub-menu__title .el-icon) {
  color: rgba(255, 255, 255, 0.95) !important;
}

:deep(.sidebar-menu .el-sub-menu .el-menu) {
  background: rgba(0, 0, 0, 0.25) !important;
  border-radius: 10px;
  margin: 8px 0 4px 0;
  padding: 6px 0;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

:deep(.sidebar-menu .el-sub-menu .el-menu-item) {
  height: 44px;
  line-height: 44px;
  padding-left: 56px !important;
  margin-bottom: 3px;
  border-radius: 8px;
  font-size: 13px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.sidebar-menu .el-sub-menu .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.08) !important;
  transform: translateX(4px);
  color: rgba(255, 255, 255, 0.95) !important;
}

:deep(.sidebar-menu .el-sub-menu .el-menu-item.is-active) {
  background: rgba(64, 158, 255, 0.25) !important;
  color: #66b1ff !important;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  transform: translateX(4px);
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 16px;
  background-color: var(--header-bg);
  color: var(--header-text);
  box-shadow: var(--shadow-sm);
  border-bottom: 1px solid var(--header-border);
  transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}

.header-left {
  display: flex;
  align-items: center;
}


.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 20px;
  cursor: pointer;
  color: var(--text-secondary);
  transition: color 0.3s;
}

.header-icon:hover {
  color: var(--color-primary);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: var(--bg-hover);
}

.username {
  margin-left: 8px;
  font-size: 14px;
  color: var(--text-primary);
}

.content {
  flex: 1;
  padding: 20px;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.content :deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

/* 过渡动画 */
.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.5s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 遮罩层 */
.sidebar-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 998;
  backdrop-filter: blur(4px);
}

/* 侧边栏滑入动画 */
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-left-enter-from,
.slide-left-leave-to {
  transform: translateX(-100%);
}

/* 遮罩层淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-container {
    width: 280px !important;
    max-width: 85vw;
  }
  
  .username {
    display: none;
  }
  
  .toggle-icon-wrapper {
    width: 44px;
    height: 44px;
  }
  
  .toggle-icon {
    font-size: 24px;
  }
}

/* 切换图标容器 */
.toggle-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-right: 16px;
  cursor: pointer;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: transparent;
  position: relative;
}

.toggle-icon-wrapper::before {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 12px;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.toggle-icon-wrapper:hover::before {
  opacity: 0.1;
}

.toggle-icon-wrapper:hover {
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(102, 177, 255, 0.05) 100%);
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.toggle-icon-wrapper:active {
  transform: scale(0.95);
}

/* 切换图标 */
.toggle-icon {
  font-size: 28px;
  color: #409EFF;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 1;
}

.toggle-icon-wrapper:hover .toggle-icon {
  color: #409EFF;
  transform: rotate(90deg) scale(1.1);
}
</style>